import 'dart:async';
import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'umeng_link_flutter_platform_interface.dart';

/// An implementation of [UmengLinkFlutterPlatform] that uses method channels.
class MethodChannelUmengLinkFlutter extends UmengLinkFlutterPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('umeng_link_flutter');

  final eventChannel = const EventChannel('umeng_link_flutter_event');

  StreamSubscription<dynamic>? streamSubscription;

  Function? eventCallback;

  MethodChannelUmengLinkFlutter() {
    streamSubscription = eventChannel?.receiveBroadcastStream().listen((event) {
      if (eventCallback != null) {
        eventCallback!(jsonDecode(event));
      }
    }) as StreamSubscription;
  }

  @override
  void setOnLinkMessage(Function callback) {
    eventCallback = callback;
  }

  @override
  Future<void> init() async {
    final version = await methodChannel.invokeMethod<void>('init');
    return version;
  }
}
